package cn.itcast.hotel;

import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.ingest.IngestStats;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Stats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class EsSearchDemo {
    @Test
    public void aggregations() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);
        source.aggregation(
                AggregationBuilders.terms("brandAgg")
                .field("brand")
                .size(20)
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Terms termsResult = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> buckets = termsResult.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            System.out.println("当前值"+keyAsString);
            System.out.println("文档数量"+bucket.getDocCount());
        }

    }
    @Test
    public void aggregations2() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);
        source.aggregation(
                AggregationBuilders.stats("stats")
                        .field("price")

        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = response.getAggregations();
        Stats termsResult = aggregations.get("stats");
        System.out.println("平均"+termsResult.getAvg());

    }

    @Test
    public void highlight() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        source.query(QueryBuilders.matchQuery("name","上海店"));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.requireFieldMatch(false);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    @Test
    public void sortAndPage() throws IOException {
        int page=1;
        int size=3;
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.sort("score", SortOrder.DESC);
        source.sort("price", SortOrder.ASC);
        source.from((page-1)*size);
        source.size(size);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    @Test
    public void bool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "上海店");
        boolQuery.must(matchQueryBuilder);
        RangeQueryBuilder price = QueryBuilders.rangeQuery("price").gte(200).lt(300);
        boolQuery.filter(price);

        source.query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    @Test
    public void range() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        source.query(QueryBuilders.rangeQuery("price").gte(100).lt(500));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    @Test
    public void term() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        source.query(QueryBuilders.matchQuery("brand", "速8"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    @Test
    public void match() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();

        source.query(QueryBuilders.matchQuery("name", "如家"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    @Test
    public void researchAll() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.matchAllQuery());

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    private void printResult(SearchResponse response) {
        SearchHits hits = response.getHits();
        System.out.println("查询到的文档数量：" + hits.getTotalHits().value);
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit searchHit : searchHits) {
            String hotelJSON = searchHit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(hotelJSON, HotelDoc.class);
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)){
                HighlightField name = highlightFields.get("name");
                String join = StringUtils.join(name.getFragments());
                hotelDoc.setName(join);
            }
            System.out.println(hotelDoc);
        }
    }

    RestHighLevelClient client;

    @BeforeEach
    public void init() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://120.48.83.4:9200")
        ));
    }

    @AfterEach
    public void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
